from rest_framework import status
from rest_framework.response import Response
from common.views.base_views import BaseAPIView
from .models import *
from apps.repo.models import Repo
from django.db.models import Q
from apps.user.models import User
from apps.order.models import SubOrder
from common.exceptions import (JsonAPIException, ParametersErrorAPIException)
from common import time_rest, int_2_2d
import datetime
import copy
from django.db import transaction
from apps.storage.models import PublicFile
import json

from .error_code import ErrCode


def val(offset, limit):
    """
    检验参数
    :param offset:
    :param limit:
    :return:
    """
    try:
        offset = int(offset)
        limit = int(limit)
    except:
        raise JsonAPIException(ErrCode.PAGE_ARG_ERROR.name, "页码参数错误", errors=[])
    return offset, limit


class GetRepoListView(BaseAPIView):
    """
    茶仓列表
    GET     /repo/repos?offset=0&limit=20
    """

    def get(self, request, *args, **kwargs):

        resp = {'count': "0", 'items': []}
        offset = request.GET.get('offset', 0)
        limit = request.GET.get('limit', 0)
        offset, limit = val(offset, limit)
        if limit == 0:
            resp['count'] = 0
            resp['items'] = []
            return Response(resp)

        count, repo = Repo.objects.filter_by_page(offset, limit)
        resp['count'] = count
        for re in repo:
            resp['items'].append({
                "id": re.id,
                "name": re.name,
                "price_per_100g_1d": re.price_per_100g_1d
            })
        return Response(resp)


class DetailRepoView(BaseAPIView):
    """
    茶仓详情
    GET     /repo/repos/:id
    """

    def get(self, request, *args, **kwargs):
        id = kwargs["id"]
        repos = Repo.objects.filter(id=id)
        if repos.count() > 0:
            repo = repos[0]
            return Response({
                "id": repo.id,
                "name": repo.name,
                "price_per_100g_1d": repo.price_per_100g_1d
            })
        else:
            raise JsonAPIException(ErrCode.RETURN_NULL.name, ErrCode.RETURN_NULL.value, [])
